﻿using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using InvoiceInvoker.Logic;

namespace InvoiceInvoker.MvcUI.Models
{
	public class PatternModel
	{
		[ScaffoldColumn(false)]
		public int Id { get; set; }

		[ScaffoldColumn(false)]
		public int RegisteredSellerId { get; set; }

		[ScaffoldColumn(false)]
		[DisplayName("Klient")]
		[Required(ErrorMessage = "Wybierz klienta")]
		[Range(1, int.MaxValue, ErrorMessage = "Wybierz klienta")]
		public int CustomerId { get; set; }

		[DisplayName("Klient")]
		[Required(ErrorMessage = "Wybierz klienta")]
		public CustomerModel Customer { get; set; }

		[DisplayName("Produkty")]
		[Required(ErrorMessage = "Wybierz produkty")]
		public List<ProductModel> Products { get; set; }

		[DisplayName("Sposób płatności")]
		[StringLength(10, ErrorMessage = "Sposób płatności może mieć co najwyżej 10 znaków")]
		public string PaymentType { get; set; }

		[DisplayName("Waluta")]
		[Required(ErrorMessage = "Podaj walutę")]
		[StringLength(10, ErrorMessage = "Waluta może mieć co najwyżej 10 znaków")]
		public string PaymentCurrency { get; set; }

		[DisplayName("Uwagi")]
		[StringLength(3000, ErrorMessage = "Uwagi mogą mieć co najwyżej 3000 znaków")]
		public string Remarks { get; set; }

		public PatternModel()
		{
			Customer = new CustomerModel();
			Products = new List<ProductModel>();
		}

		public PatternModel(int registeredSellerId)
		{
			RegisteredSellerId = registeredSellerId;

			Customer = new CustomerModel();
			Products = new List<ProductModel>();
			PaymentCurrency = "PLN";
		}

		public PatternModel (InvoicePattern invoicePattern)
		{
			Id = invoicePattern.Id;
			RegisteredSellerId = invoicePattern.RegisteredSellerId ?? 0;
			Customer = new CustomerModel(invoicePattern.RegisteredCustomer);
			CustomerId = Customer.Id;
			PaymentType = invoicePattern.PaymentType;
			PaymentCurrency = invoicePattern.PaymentCurrency;
			Remarks = invoicePattern.Remarks;

			Products = new List<ProductModel>();
			foreach (var item in invoicePattern.InvoicePatternRegisteredProducts)
				Products.Add(new ProductModel(item.RegisteredProduct));

			Products.Sort((a, b) => a.Name.CompareTo(b.Name));
		}

		public InvoicePattern ToInvoicePattern()
		{
			InvoicePattern result = new InvoicePattern();
			result.Id = Id;
			result.RegisteredSellerId = RegisteredSellerId;
			result.RegisteredCustomerId = CustomerId;
			result.PaymentType = PaymentType;
			result.PaymentCurrency = PaymentCurrency;
			result.Remarks = Remarks;

			return result;
		}
	}
}